package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Selection;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.event.CollectEvent;
import com.cljz.makepassenger.model.net.bean.ActivityListBean;
import com.cljz.makepassenger.present.activity.MineCollectP;
import com.cljz.makepassenger.ui.ItemDecoration.LinearSpacesItemDecoration;
import com.cljz.makepassenger.ui.adapter.NearByListAdapter;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.widget.ClearEditText;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/27.
 */

public class MineCollectActivity extends BaseActivity<MineCollectP> implements NearByListAdapter.OnItemClickListener, XRecyclerView.LoadingListener, BDLocationListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.fl_title_right)
    FrameLayout flTitleRight;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.cet_collect_search)
    ClearEditText cetCollectSearch;
    @BindView(R.id.xrv_my_collect)
    XRecyclerView xrvMyCollect;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.iv_title_right1)
    ImageView ivTitleRight1;
    @BindView(R.id.fl_title_right1)
    FrameLayout flTitleRight1;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.btn_empty)
    Button btnEmpty;
    @BindView(R.id.rl_empty)
    RelativeLayout rlEmpty;
    @BindView(R.id.rl_collect_search)
    RelativeLayout rlCollectSearch;
    private NearByListAdapter nearByListAdapter;
    private List<ActivityListBean.DataBean> myCollectList;
    private int page = 1;
    private boolean isLoadMore = false;
    private boolean isRefresh = false;
    private String key = "";
    private LocationClient mLocationClient;
    private double latitude;
    private double longitude;
    private boolean isFirst;
    private int changePosition;
    private int clickPosition = -1;

    @Override
    public void initData(Bundle savedInstanceState) {
        isFirst = true;
        initLocation();
        tvTitleName.setText("我的收藏");
        tvTitleRight.setText("更多活动");
        tvEmpty.setText("您当前没有收藏的活动");
        rlEmpty.setVisibility(View.GONE);
        tvTitleRight.setTextColor(getResources().getColor(R.color.txt_black_color));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        xrvMyCollect.setLayoutManager(linearLayoutManager);
        ((SimpleItemAnimator) xrvMyCollect.getItemAnimator()).setSupportsChangeAnimations(false);
        nearByListAdapter = new NearByListAdapter(this, myCollectList);
        xrvMyCollect.setAdapter(nearByListAdapter);
        xrvMyCollect.addItemDecoration(new LinearSpacesItemDecoration(20));
        xrvMyCollect.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        xrvMyCollect.setLoadingMoreEnabled(true);
        xrvMyCollect.setPullRefreshEnabled(true);
    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(rlCollectSearch)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(cetCollectSearch, 0);
                    }
                });
        RxView.clicks(btnEmpty)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .putInt("type", EditorInvitedActivity.EDITOR_INVITE)
                                .to(EditorInvitedActivity.class)
                                .launch();
                    }
                });
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.pop(MineCollectActivity.this);
                    }
                });
        RxView.clicks(flTitleRight)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(NearbyActivity.class)
                                .launch();
                    }
                });
        xrvMyCollect.setLoadingListener(this);
        nearByListAdapter.setOnItemClickListener(this);
        RxTextView.textChanges(cetCollectSearch)
                .compose(this.<CharSequence>bindToLifecycle())
                .subscribe(new Action1<CharSequence>() {
                    @Override
                    public void call(CharSequence charSequence) {
                        Selection.setSelection(cetCollectSearch.getText(), charSequence.length());
                        xrvMyCollect.setNoMore(false);
                        if (charSequence.length() == 0) {
                            key = "";
                        } else {
                            key = charSequence.toString().trim();
                        }
                        page = 1;
                        L.e("1_net", key);
                        xrvMyCollect.refresh();
                    }
                });

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_collect;
    }

    @Override
    public MineCollectP newP() {
        return new MineCollectP();
    }


    @Override
    public void onClick(List<ActivityListBean.DataBean> activityList, int position) {
        Router.newIntent((Activity) App.getInstance()).to(InvitationLetterActivity.class).putInt("type", InvitationLetterActivity.ACTIVITY).putString("id", activityList.get(position).getId()).launch();
        clickPosition = position;
    }

    @Override
    public void onCollectClick(List<ActivityListBean.DataBean> activityList, int position) {
        this.myCollectList = activityList;
        L.e(position + "::position");
        changePosition = position;
        ActivityListBean.DataBean dataBean = activityList.get(changePosition);
        if ("0".equals(dataBean.getIs_collection())) {
            getP().collection(dataBean.getId());
        } else {
            getP().collectionCancel(dataBean.getId());
        }
    }

    @Override
    public void onLongClick(ActivityListBean.DataBean dataBean) {

    }


    @Override
    public void onRefresh() {
        page = 1;
        isRefresh = true;
        getP().collectionMy(page, key, latitude, longitude);
    }

    @Override
    public void onLoadMore() {
        page++;
        isLoadMore = true;
        getP().collectionMy(page, key, latitude, longitude);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stop();
    }

    private void initLocation() {
        //声明LocationClient类
        mLocationClient = new LocationClient(getApplicationContext());


        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 180000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(false);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);

        //注册监听函数
        mLocationClient.registerLocationListener(this);
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //获取纬度信息
        latitude = bdLocation.getLatitude();
        //获取经度信息
        longitude = bdLocation.getLongitude();
        L.e("latitude:" + latitude + ",longitude:" + longitude);
        if (isFirst) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    xrvMyCollect.refresh();
                    isFirst = false;
                }
            });

        }
    }


    public void getCollectMySucceed(List<ActivityListBean.DataBean> dataBeanList) {
        dismissLoadingDialog();
        if (isLoadMore) {
            xrvMyCollect.loadMoreComplete();
            if (dataBeanList.size() == 0) {
                xrvMyCollect.setNoMore(true);
            } else {
                nearByListAdapter.addData(dataBeanList);
            }
            isLoadMore = false;
        } else if (isRefresh) {
            myCollectList = dataBeanList;
            isRefresh = false;
            xrvMyCollect.refreshComplete();
            if ("".equals(key)) {
                tvEmpty.setText("您当前没有收藏的活动");
            } else {
                tvEmpty.setText("您搜索的活动不存在");
            }
            if (myCollectList.size() == 0) {
                rlEmpty.setVisibility(View.VISIBLE);
                xrvMyCollect.setVisibility(View.GONE);
            } else {
                rlEmpty.setVisibility(View.GONE);
                xrvMyCollect.setVisibility(View.VISIBLE);
                nearByListAdapter.setData(myCollectList);
                xrvMyCollect.setNoMore(false);
            }
        }
    }

    public void getCollectMyFail(String error) {
        dismissLoadingDialog();
        xrvMyCollect.refreshComplete();
        showToast(error, R.mipmap.jinshi);
    }

    public void collectionSucceed(String msg) {
        ActivityListBean.DataBean dataBean = myCollectList.get(changePosition);
        dataBean.setIs_collection("1");
        myCollectList.set(changePosition, dataBean);
        nearByListAdapter.setData(myCollectList);
        showToast(msg, R.mipmap.nearby_success);
        BusProvider.getBus().post(new CollectEvent());

    }

    public void collectionFail(String error) {
        showToast(error, R.mipmap.jinshi);
    }

    public void collectionCancelSucceed(String msg) {
        ActivityListBean.DataBean dataBean = myCollectList.get(changePosition);
        dataBean.setIs_collection("0");
        myCollectList.remove(changePosition);
        nearByListAdapter.setDataWithoutNotify(myCollectList);
        nearByListAdapter.notifyItemRemoved(changePosition + 1);
        nearByListAdapter.notifyItemRangeChanged(changePosition + 1,myCollectList.size() - changePosition);
        showToast(msg, R.mipmap.nearby_success);
        BusProvider.getBus().post(new CollectEvent());

    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    public void bindEvent() {
        super.bindEvent();
        BusProvider.getBus().toObservable(CollectEvent.class)
                .compose(this.<CollectEvent>bindToLifecycle())
                .subscribe(new Action1<CollectEvent>() {
                    @Override
                    public void call(CollectEvent collectEvent) {
                        L.e("CollectEvent");
                        if (clickPosition != -1) {
                            if (collectEvent.getHasCollect() != null) {
                                if (!collectEvent.getHasCollect()) {
                                    myCollectList.remove(clickPosition);
                                    nearByListAdapter.setData(myCollectList);
                                }

                            }
                        }
                    }
                });
    }

    public void collectionCancelFail(String error) {
        showToast(error, R.mipmap.jinshi);
    }

}


